// pages/index/detail/thematic/index.js
var app = getApp();
var time_go = '';
Page({

	/**
	 * 页面的初始数据
	 */
  data: {
    images: {},
    banner_index: 0,
    Banner_size: [],
    //优惠劵
    imgurl: app.urlimg,
    coupon: [],
    //分类导航
    choose: [
    ],
    //导航条/分区
    all: [],
    // 专题页面的广告模板
    picture: [],
    //页尾
    topic_img: [],

  },
  // 进入搜索页面
  search_click: function () {
    wx.navigateTo({
      url: '/pages/search/index'
    })
  },
  // 领取优惠劵
  pick: function (e) {
    var couponId = e.currentTarget.dataset.id;
    var that = this;
    var index = e.currentTarget.dataset.index;
    wx.request({
      url: app.url + "?controller=api_coupon&action=receive",
      data: {
        couponId: couponId
      },
      header: {
        'content-type': 'application/json', // 默认值
        'token': wx.getStorageSync('token_key')
      },
      success: function (res) {
        console.log(res);
        var coupon = that.data.coupon;
        console.log(coupon);
        if (res.data.result) {
          if (coupon[index].restricts != 0) {
            coupon[index].restricts--;
            wx.showToast({
              title: '优惠劵领取成功',
              icon: 'success',
              duration: 500,
              mask: true,
            })
            that.setData({
              coupon: coupon,
            })
          } else {
            wx.showToast({
              title: '您已经领取完了哦~',
              icon: 'loading',
              duration: 500,
              mask: true,
            })
          }
        }
      }
    })
  },
  //倒计时banner
  imageLoad: function (e) {
    console.log(e);
    var $width = e.detail.width,    //获取图片真实宽度
      $height = e.detail.height,
      ratio = $width / $height;    //图片的真实宽高比例
    var viewWidth = 718,           //设置图片显示宽度，左右留有16rpx边距
      viewHeight = 718 / ratio;    //计算的高度值
    var image = this.data.images;
    //将图片的datadata-index作为image对象的key,然后存储图片的宽高值
    console.log(e.target.dataset.index);
    image[e.target.dataset.index] = {
      width: viewWidth,
      height: viewHeight
    }
    this.setData({
      images: image
    })
  },
  // 分类导航
  navigation_click: function (e) {
    var id = e.currentTarget.dataset.id;
    console.log("分类导航");
    // wx.navigateTo({ 
    // 	url: '' 
    // })
  },
  mores: function (e) {
    var id = e.currentTarget.id;
    console.log("分类导航" + id);
    console.log(e);
    wx.redirectTo({ url: '/pages/goods/index?footer_cat_ids=' + id })
  },
  // 响应商品点击
  goods_click: function (e) {
    var index = e.currentTarget.dataset.index;
    //console.log(e)
    wx.navigateTo({ url: '/pages/index/detail/index?id=' + index })
  },
  // 专题页页面的广告模板
  advertising_click: function (e) {
    console.log(e.currentTarget.dataset.url);
    var url = e.currentTarget.dataset.url;
    wx.redirectTo({
      url: url,
    })
  },
  // 底部banner点击事件
  topic_click: function (e) {
    var index = e.currentTarget.dataset.index;
    console.log("底部banner点击事件");
    wx.redirectTo({ url: '/pages/index/detail/index?id=' + index })
  },
	/**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function (e) {
    var that = this;

    if (wx.getStorageSync('token_key') == undefined || wx.getStorageSync('token_key') == '') {
      app.getUserInfo(function () {
        load_fn();
      })
    } else {
      load_fn()
    }

    function load_fn() {
      if (typeof (e.id) == 'undefined') {
        e.id = 2;
      }
      wx.request({
        url: app.url + 'api_topic/topic_info',
        data: {
          id: e.id,
        },
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token_key')
        }, success: function (json) {
          console.log(json);
          wx.setNavigationBarTitle({
            title: json.data.result.topic.topic_title,
          })
          console.log(json.data.result);

          var current_time = Date.parse(new Date()) / 1000;
          var end_time = json.data.result.topic.topic_end_time;
          console.log(end_time - current_time);
          if (current_time < end_time) {
            time_computations(end_time - current_time, that);
          } else {
            clearInterval(time_go);
          }

          console.log(json.data.result);
          var banner_box = json.data.result.topic_photo.banner;
          var imgarr = imageForeach(banner_box, 1);//默认取一张
          console.log(imgarr);
          that.setData({
            data: json.data.result,
            loadHidden: true,
            time: end_time,
            current_time: current_time,
            picture: json.data.result.indexTopic,
            bannerImages: imgarr,
          })
        }
      });

      //加载优惠券列表
      wx.request({
        url: app.url + 'api_coupon/canReceive',
        data: {
          topicId: e.id
        },
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token_key')
        },
        success: function (json) {
          var data = json.data.result;
          console.log(data);
          for (var obj in data) {
            // var reg = /([^\s]+)\s.*/;
            // var str01 = getLocalTime(data[obj].start_time);
            // var str02 = getLocalTime(data[obj].end_time);
            // data[obj].start_time = str01.replace(reg);
            // data[obj].end_time = str02.replace(reg);

            data[obj].start_time = getLocalTime(data[obj].start_time);
            data[obj].end_time = getLocalTime(data[obj].end_time);

            that.data.coupon.push(data[obj]);
          }
          function getLocalTime(nS) {
            return new Date(parseInt(nS) * 1000).toLocaleString().substr(0, 10);
          }
          that.setData({
            coupon: data,
          });
        }
      })
    }
  },
  bannerImagesLoad: function (e) {
    var that = this
    var $width = e.detail.width,    //获取图片真实宽度
      $height = e.detail.height,
      ratio = $width / $height;    //图片的真实宽高比例
    var viewWidth = 750,           //设置图片显示宽度，左右留有16rpx边距
      viewHeight = 750 / ratio;    //计算的高度值
    var image = this.data.Banner_size;
    //将图片的datadata-index作为image对象的key,然后存储图片的宽高值
    image[e.target.dataset.index] = {
      width: viewWidth,
      height: viewHeight
    }
    //加载完再加载一张
    var imgarr = imageForeach(that.data.data.topic_photo.banner, that.data.banner_index + 2)
    var aa = that.data.banner_index + 1
    that.setData({
      banner_index: that.data.banner_index + 1,
      bannerImages: imgarr,
      Banner_size: image,
    })
  },
  photolink: function (e) {
    var that = this
    var url = e.currentTarget.dataset.url
    if (url !== '') {
      wx.redirectTo({ url: url })
    }
  },
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
  onReady: function () {

  },

	/**
	 * 生命周期函数--监听页面显示
	 */
  onShow: function () {
    var that = this;
    time_go = setInterval(function () {
      var current_time = Date.parse(new Date()) / 1000;
      var end_time = that.data.time;
      if (current_time < end_time) {
        that.setData({
          time: end_time,
          current_time: current_time,
        })
        time_computations(end_time - current_time, that);
      } else {
        clearInterval(time_go);
      }
    }, 1000);
  },

	/**
	 * 生命周期函数--监听页面隐藏
	 */
  onHide: function () {
    clearInterval(time_go);
  },

	/**
	 * 生命周期函数--监听页面卸载
	 */
  onUnload: function () {
    clearInterval(time_go);
  },

	/**

	/**
	 * 页面上拉触底事件的处理函数
	 */
  onReachBottom: function () {

  },
})



function time_computations(Times, that) {
  // console.log(Times);

  var day = Math.floor(Times / (60 * 60 * 24));//计算剩余的天数

  var hours = parseInt(Times / 60 / 60 % 24, 10); //计算剩余的小时
  if (('' + hours).length == 1) {
    hours = '0' + hours;
  }
  var minutes = parseInt(Times / 60 % 60, 10);//计算剩余的分钟
  if (('' + minutes).length == 1) {
    minutes = '0' + minutes;
  }
  var seconds = parseInt(Times % 60, 10);//计算剩余的秒数
  if (('' + seconds).length == 1) {
    seconds = '0' + seconds;
  }
  //倒计时判断
  var new_time = [];
  new_time[0] = day;
  new_time[1] = hours;
  new_time[2] = minutes;
  new_time[3] = seconds;

  that.setData({
    new_time: new_time,
  })
};

// banner 一张一张加载
function imageForeach(photo, num) {
  var img = photo;
  // var url = app.urlimg;
  var imgs = new Array;
  var i = 0;
  img.forEach(function (e) {
    if (i < num) {
      imgs.push(e);
      i++;
    }
  })
  return imgs;
};